import hashlib
import re
import time
import platform
import sys
from loguru import logger
import my_fake_useragent as ua1
from urllib.parse import urljoin
from urllib.parse import urlparse
from urllib.parse import urlunparse
from posixpath import normpath
from lxml import etree

if platform.system().lower() == 'linux':
    sys.path.append("/home/xinzhi")

ua = ua1.UserAgent(family="chrome").random()


# url补全
def url_replenish(url, base):
    if not url:
        return ''
    url1 = urljoin(base, url)
    arr = urlparse(url1)
    path = normpath(arr[2])
    return urlunparse((arr.scheme, arr.netloc, path, arr.params, arr.query, arr.fragment))


def timestamp_to_date(time_stamp, format_string="%Y-%m-%d %H:%M:%S"):
    try:
        if time_stamp:
            time_array = time.localtime(time_stamp)
            str_date = time.strftime(format_string, time_array)
            return str_date
        else:
            return ''
    except:
        return ''


def date_to_timestamp(str_date, format_string="%Y-%m-%d %H:%M:%S"):
    try:
        starttimeArray = time.strptime(str_date, format_string)
        starttimestamp = time.mktime(starttimeArray)
        return starttimestamp
    except:
        return 0


# 链接md5
def create_md5(md_str):
    m = hashlib.md5()
    b = (md_str).encode(encoding='utf-8')
    m.update(b)
    only_id_md5 = m.hexdigest()
    return only_id_md5


# 学校cid
def create_cid(school_name):
    m = hashlib.md5()
    b = (school_name).encode(encoding='utf-8')
    m.update(b)
    only_id_md5 = m.hexdigest()
    return only_id_md5[8:24].upper()


def data_filter(con: str, _id=None):
    try:
        assert re.search(r'^\s*$', con, re.DOTALL) is None, '内容仅为空白字符'
        escape_con = re.sub(r'\s+', ' ', etree.HTML(text=con).xpath('string(.)'))
        return escape_con if re.search(r'^\s*$', escape_con, re.DOTALL) is None else ''
    except AssertionError as e:
        if str(e) == '内容仅为空白字符':
            return ""
        logger.debug(f'ID: {_id}  MSG: {e}')
        return False
    except Exception as e:
        logger.exception(f'过滤发生异常 ID: {_id}  MSG: {e}')
        return False


if __name__ == '__main__':
    print(timestamp_to_date(int(time.time())))
